﻿#include "com_vguang_VbarSo.h"
#include "vbar/channel.h"

#include <stdlib.h>
#include <stdio.h>

/*
 * Class:     com_vguang_VbarSo
 * Method:    vbar_channel_open
 * Signature: (I[B)I
 */
JNIEXPORT jint JNICALL Java_com_vguang_VbarSo_vbar_1channel_1open
  (JNIEnv *env, jclass jcls, jint jtype, jbyteArray jarg)
{
	LOGI("Begin Java_com_vguang_VbarSo_vbar_1channel_1open");
	
	unsigned char *pBuffer = (*env)->GetByteArrayElements(env, jarg, 0);
	if(!pBuffer)
	{
		//LOGI("GetByteArrayElements Failed!");
		return 0;
	}

	//LOGI("pBuffer1:%s", pBuffer);
	struct vbar_channel *pchannel = vbar_channel_open(jtype, (unsigned long)pBuffer);



	(*env)->ReleaseByteArrayElements(env, jarg, pBuffer, 0);
	
	return (unsigned int)pchannel;
}

/*
 * Class:     com_vguang_VbarSo
 * Method:    vbar_channel_send
 * Signature: (I[BI)I
 */
JNIEXPORT jint JNICALL Java_com_vguang_VbarSo_vbar_1channel_1send
  (JNIEnv *env, jclass jcls, jint jchannel, jbyteArray jbuffer, jint jlength)
{
	LOGI("Begin Java_com_vguang_VbarSo_vbar_1channel_1send");
	
	unsigned char *pBuffer = (*env)->GetByteArrayElements(env, jbuffer, 0);
	if(!pBuffer)
	{
		LOGI("GetByteArrayElements Failed!");
		return 0;
	}

	LOGI("pBuffer:%s", pBuffer);

	jint jresult = vbar_channel_send((struct vbar_channel *)jchannel, pBuffer, jlength);


	(*env)->ReleaseByteArrayElements(env, jbuffer, pBuffer, 0);
	


	return jresult;
}


/*
 * Class:     com_vguang_VbarSo
 * Method:    vbar_channel_recv
 * Signature: (I[BII)I
 */
JNIEXPORT jint JNICALL Java_com_vguang_VbarSo_vbar_1channel_1recv
  (JNIEnv *env, jclass jcls, jint jchannel, jbyteArray jbuffer, jint jsize, jint jmilliseconds)
{
	//LOGI("Begin Java_com_vguang_VbarSo_vbar_1channel_1recv");
	
	unsigned char *pBuffer = (unsigned char*)malloc(jsize);
	jint jresult = vbar_channel_recv((struct vbar_channel *)jchannel, pBuffer, jsize, jmilliseconds);

	(*env)->SetByteArrayRegion(env, jbuffer, 0, jsize, pBuffer);

	LOGI("pBuffer 1:%x", pBuffer[1]);
	LOGI("pBuffer 2:%x", pBuffer[2]);
	LOGI("pBuffer 3:%x", pBuffer[3]);
    LOGI("pBuffer 4:%x", pBuffer[4]);
    LOGI("pBuffer 5:%x", pBuffer[5]);
    LOGI("pBuffer 6:%x", pBuffer[6]);

	free(pBuffer);

	return jresult;
}


/*
 * Class:     com_vguang_VbarSo
 * Method:    vbar_channel_close
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_com_vguang_VbarSo_vbar_1channel_1close
  (JNIEnv *env, jobject jobj, jint jchannel)
{
	//LOGI("Begin Java_com_vguang_VbarSo_vbar_1channel_1close");
	vbar_channel_close((struct vbar_channel *)jchannel);
	
	return;
}


